use algo_lib::stack::Stack;
use std::str;


// 括号匹配
fn par_checker(par: &str) -> bool {
    let mut char_list = Vec::new();
    for c in par.chars() {
        char_list.push(c);
    }

    let mut index = 0;
    let mut balance = true;
    let mut stack = Stack::new();
    while index < char_list.len() && balance {
        let c = char_list[index];
        match c {
            '(' | '[' | '{'  => stack.push(c),
            ')'|']'|'}' => {
                if stack.is_empty() {
                    balance = false;
                } else {
                    let top = stack.pop().unwrap();
                    if !_par_match(top, c) {
                        balance = false;
                    }
                }
            },
            _ => {}
        }
        index += 1;
    }
    balance && stack.is_empty()
}

fn _par_match(open: char, close: char) -> bool {
    let opens = "([{";
    let closes = ")]}";
    opens.find(open) == closes.find(close)
}

pub fn run_par_checker1() {
    let sa = "(){(())}";
    let sb = "()[(()";
    let sc = "()[fun](a+b)()";
    let sd = "(1+4)*(3-";
    let r1 = par_checker(sa);
    let r2 = par_checker(sb);
    let r3 = par_checker(sc);
    let r4 = par_checker(sd);
    println!("sa balanced: {r1}, sb balanced:{r2}, sc balanced: {r3}, sd balanced: {r4}");
}

// 进制转换
fn base_converter(mut dec_num: u32, base: u32) -> String {
    let digits = ['0','1','2','3','4','5','6','7','8','9','A','B',
    'C','D','E','F'];

    let mut rem_stack = Stack::new();
    while dec_num > 0 {
        rem_stack.push(dec_num % base);
        dec_num /= base;
    }

    let mut bin_v = vec![];
    while !rem_stack.is_empty() {
        let t = rem_stack.pop().unwrap();
        bin_v.push(t);
    }

    println!("bin: {:?}", bin_v);

    bin_v.into_iter().map(|d| digits[d as usize]).collect()
}

pub fn run_base_converter() {
    let bin_s = base_converter(11,2);
    println!("10 is b {bin_s}");
    let s_11 = base_converter(33,8);
    println!("10 is b {s_11}");
}